package com.jackrain.nea.fc.dl.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jackrain.nea.common.QueryCpUtil;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.fc.dl.api.VIewOrderSignCmd;
import com.jackrain.nea.fc.dl.mapper.ViewBatchUpdateMaper;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.QueryCmd;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "dl")
public class ViewOrderSignCmdImpl extends CommandAdapter implements VIewOrderSignCmd {


    @Reference(version = "2", group = "cp")
    private QueryCmd queryCmd;

    @Autowired
    QueryCpUtil postQueryEvemt;

    @Override
    public ValueHolder execute(HashMap map) throws NDSException {


        JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(map.get("param"), "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
        log.info("ViewOrderSignCmdImpl--param-->{}",param);

        if (null == param || (!param.containsKey("IDS")) || param.getJSONArray("IDS").size() <= 0) {
            throw new NDSException("参数格式错误！");
        }
        ValueHolder vh = new ValueHolder();

        ViewBatchUpdateMaper viewBatchUpdateMaper = ApplicationContextHandle.getBean(ViewBatchUpdateMaper.class);
//        JSONArray dataArray = param.getJSONArray("IDS");
        List<HashMap> mapList = new ArrayList<>();
        List<HashMap> idsList = new ArrayList<>();

        Object[] list = (Object[]) param.getJSONArray("IDS").toArray();
        String type = param.getString("type");
        if ("dlsource".equals(type)) {
            mapList = viewBatchUpdateMaper.selComOrderSign(list);

        } else {

            List<HashMap> boxIdlist = viewBatchUpdateMaper.selBoxId(list);

            if ((boxIdlist == null) || (boxIdlist.size() <= 0)) {
                vh.put("code", 2);
                vh.put("message", "无对应的TRAN_B_BILL_BOX_ID!");
                return vh;
            }
            JSONArray sb1 = new JSONArray();
            JSONArray ids = new JSONArray();
            for (HashMap hashMap : boxIdlist) {
                Long num = (Long) hashMap.get("TRAN_B_BILL_BOX_ID");
                if(num != null){
                    sb1.add(num);
                }else{
                    Long id = (Long) hashMap.get("ID");
                    ids.add(id);
                }
            }
            Object[] objects = sb1.toArray();

            mapList = viewBatchUpdateMaper.selOrderSign(objects);

            //拣货单中掺杂的调拨单
            if(ids.size()>0){
                List<HashMap> mergeId = new ArrayList<>();
                Object[] idslist = ids.toArray();
                //查询明细表中的主表ID
                mergeId = viewBatchUpdateMaper.selMergeId(idslist);
                //查询主表数据
                JSONArray mergeIdArr = new JSONArray();
                mergeId.forEach(HashMap->
                          mergeIdArr.add(HashMap.get("DL_B_TRAN_MERGE_ID"))
                        );

                idsList = viewBatchUpdateMaper.selComOrderSign(mergeIdArr.toArray());
            }
        }

        if ((mapList == null || mapList.size() <= 0)&& idsList.size()<=0) {

            vh.put("code", 2);
            vh.put("message", "无相应数据!");
            return vh;

        }

        JSONArray dataArray = listToJsonarray(mapList);
        JSONArray idsArray = listToJsonarray(idsList);
        JSONArray resultArray = new JSONArray();

        String date = "";
        for (int i = 0; i < dataArray.size(); i++) {
            JSONObject dataJo = new JSONObject();
            JSONObject mainJo = dataArray.getJSONObject(i);
            String billno = mainJo.getString("BILL_NO");
            String signTime;
            if ("dlsource".equals(type)) {
                signTime = mainJo.getString("ACCEPT_TIME");
            } else {
                signTime = mainJo.getString("ARRIVAL_TIME");
            }
            date = signTime;
            dataJo.put("orderId", billno);
            dataJo.put("signTime", signTime);
            resultArray.add(dataJo);
        }
        if(idsArray.size()>0){
            for (int i = 0; i < idsArray.size(); i++) {
                JSONObject dataJo = new JSONObject();
                JSONObject mainJo = idsArray.getJSONObject(i);
                String billno = mainJo.getString("BILL_NO");
                String signTime= mainJo.getString("ACCEPT_TIME");
                if(signTime==null){
                    dataJo.put("signTime", date);
                }else{
                    dataJo.put("signTime", signTime);
                }
                dataJo.put("orderId", billno);
                resultArray.add(dataJo);
            }
        }
        log.info("ViewOrderSignCmdImpl--resultArray-->{}",resultArray);
        vh.put("data", resultArray);
        vh.put("code", 0);
        vh.put("message", "查询成功");
        return vh;
    }

    public Date stringToDate(String str) {

        SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD HH:mm:ss");//小写的mm表示的是分钟
        Date mdate = null;
        try {
            mdate = sdf.parse(str);

        } catch (Exception e) {
            throw new NDSException(e.getMessage());
        }
        return mdate;
    }

    /**
     * list转jsonarray
     *
     * @param mapList
     * @return jsonArray
     */
    public JSONArray listToJsonarray(List<HashMap> mapList) {
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < mapList.size(); i++) {
            HashMap map = (HashMap) mapList.get(i);
            JSONObject jsonObject = new JSONObject(map);
            JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(jsonObject, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
            jsonArray.add(param);
        }
        return jsonArray;
    }

}
